<template>
  <view class="container">
    <!-- 左右眼选择 -->
    <view class="section">
      <view class="section-title">左右眼选择</view>
      <view class="eye-select-container">
        <view class="eye-select-btn" v-for="(item, key) in lensOptions" :key="key"
           @click="selectEyeType(item.value)">
          <image :src="item.img" class="eye-image" mode="widthFix"></image>
        </view>
      </view>
    </view>

    <!-- 镜片选择 -->
    <view class="section">
      <view class="section-title">镜片选择</view>
      <view class="lens-grid">
        <!-- 使用v-for循环渲染根据当前眼睛类型筛选后的镜片选项 -->
        <view v-for="item in filteredFilmOptions" :key="item.goodsName" class="lens-item"
          :class="{ active: formData.selectedFilm === item.goodsName }" @click="selectFilmOption(item)">
          <view class="lens-image">
            <image :src="item.goodsPic" class="lens-image" mode="widthFix"></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格信息 -->
    <view>
      <view class="price-info-container">
        <!-- 总价 -->
        <view class="price-item total-price">
          <text class="price-value-icon">¥</text>
          <text class="price-value total">{{ money }}</text>
        </view>
      </view>
    </view>

    <!-- 底部购买按钮 -->
    <view class="bottom-bar">
      <button class="buy-button" @click="confirmLensSelection">确认支付</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      goodsDetail: null,
      money: '',
      goodsIds: null,
      selectedSwitchKey: '',
      showLensModal: false,
      orderType: '', // 订单类型
      lensOptions: [
        { label: '双眼', value: 0, img: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/goods/eye-two.png' },
        { label: '左眼', value: 1, img: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/goods/eye-left.png' },
        { label: '右眼', value: 2, img: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/goods/eye-right.png' },
      ],
      filmOptions: [],
      formData: {
        lensQuantity: 0,
        selectedFilm: 0, // 默认选中第一个镜片类型
        goodsId: 0,
      }
    }
  },
  onLoad(options) {
    console.log(options)
    this.goodsIds = options.goodsIds
    if (this.goodsIds) {
      this.fetchGoodsDetail()
      this.orderType = options.orderType
    }
  },
  computed: {
    // 获取选中的镜片类型名称
    getSelectedFilmName() {
      const selectedFilm = this.filmOptions.find(item => item.value === this.formData.selectedFilm);
      return selectedFilm ? selectedFilm.label : '';
    },
    
    // 获取选中的眼睛类型名称
    getSelectedEyeName() {
      const selectedEye = this.lensOptions.find(item => item.value === this.formData.lensQuantity);
      return selectedEye ? selectedEye.label : '';
    },
    
    // 计算镜片数量
    lensQuantity() {
      // 双眼为2片，左眼或右眼为1片
      return this.formData.lensQuantity === 0 ? 2 : 1;
    },
    
    // 计算属性：根据当前选中的眼睛类型筛选镜片选项
    filteredFilmOptions() {
      if (!Array.isArray(this.goodsDetail)) return [];
      
      // 根据选中的眼睛类型确定要显示的eyeType
      const selectedEyeType = this.formData.lensQuantity === 0 ? 2 : 1; // 0表示双眼，对应eyeType=2；1或2表示单眼，对应eyeType=1
      
      // 返回筛选后的商品选项
      return this.goodsDetail.filter(item => item.eyeType === selectedEyeType);
    }
  },
  
  methods: {
    // 选择镜片选项
    selectFilmOption(item) {
      for (let i = 0; i < this.filteredFilmOptions.length; i++) {
        const element = this.filteredFilmOptions[i];
        element.goodsPic = element.goodsPic.replace('-select.png', '.png')
      }
      this.formData.selectedFilm = item.goodsName;
      item.goodsPic = item.goodsPic.split('.png')[0] + '-select.png'
      this.money = item.goodsPrice || item.money;
      this.formData.goodsId = item.id
    },
    // // 获取镜片描述信息
    // getLensDescription(value) {
    //   const descMap = {
    //     0: '防水防油污，易清洁',
    //     1: '提升透光率，视野更清晰',
    //     2: '有效过滤电子屏幕蓝光',
    //     3: '增强耐磨性，延长使用寿命'
    //   }
    //   return descMap[value] || ''
    // },

    // 获取商品详情
    fetchGoodsDetail() {
      const that = this
      this.$http.GET('/app/order/order/getGoodsListById', {
        goodsId: that.goodsIds
      }, (res) => {
        that.goodsDetail = res.data;
        console.log(res)
        
        // 根据新的数据结构，处理返回的数组数据
        if (Array.isArray(res.data) && res.data.length > 0) {
          // 遍历res.data数组，将所有商品项添加到filmOptions数组中
          that.filmOptions = res.data.map(item => ({
            label: item.goodsName,
            value: item.id,
            img: item.goodsPic,
            money: item.goodsPrice, // 使用商品价格作为money值
            eyeType: item.eyeType // 保存眼睛类型信息
          }));

          that.lensOptions[0].img = that.lensOptions[0].img.split('.png')[0] + '-select.png'
          // 根据当前选中的眼睛类型设置初始价格
          const filteredItems = that.filteredFilmOptions;
          that.filteredFilmOptions[0].goodsPic = that.filteredFilmOptions[0].goodsPic.split('.png')[0] + '-select.png'
          if (filteredItems.length > 0) {
            that.formData.selectedFilm = filteredItems[0].goodsName;
            that.formData.goodsId = filteredItems[0].id;
            that.money = filteredItems[0].goodsPrice || filteredItems[0].money;
          }
        }
      }, (err) => {
        console.error('请求接口失败', err);
        uni.showToast({
          title: '请求接口失败',
          icon: 'none'
        });
      })
    },
    goToBuy() {
      const that = this
      // 检查是否有switchList参数
      if (that.goodsDetail && that.goodsDetail.switchList && Object.keys(that.goodsDetail.switchList).length > 0) {
        // 显示自定义弹窗
        that.showLensModal = true;
      } else {
        // 没有switchList参数，直接创建订单
        that.createOrder();
      }
    },

    // 关闭镜片选择弹窗
    closeLensModal() {
      this.showLensModal = false;
    },

    // 选择镜片
    selectLens(key, lens) {
      this.formData.selectedFilm = key;
    },

    // 选择眼睛类型
    selectEyeType(value) {
      this.formData.lensQuantity = value;
      // console.log(value)
      // 切换眼睛类型后，重置镜片选择为筛选后的第一个选项
      const filteredItems = this.filteredFilmOptions;
      this.lensOptions.forEach(item => {
        item.img = item.img.replace('-select.png', '.png')
      })
      this.lensOptions[value].img = this.lensOptions[value].img.split('.png')[0] + '-select.png'
      for (let i = 0; i < filteredItems.length; i++) {
        const element = filteredItems[i];
        element.goodsPic = element.goodsPic.replace('-select.png', '.png')
      }
      if (filteredItems.length > 0) {
        this.formData.selectedFilm = filteredItems[0].goodsName;
        this.formData.goodsId = filteredItems[0].id;
        filteredItems[0].goodsPic = filteredItems[0].goodsPic.split('.png')[0] + '-select.png'
        this.money = filteredItems[0].goodsPrice || filteredItems[0].money;
      }
    },
    
    // 确认选择镜片
    confirmLensSelection() {
      if (typeof this.formData.selectedFilm !== 'undefined') {
        this.createOrderWithSwitchKey();
        this.showLensModal = false;
      } else {
        uni.showToast({
          title: '请选择镜片',
          icon: 'none'
        });
      }
    },
    // 创建订单方法（包含switchKey）
    createOrderWithSwitchKey() {
      const that = this
      let params = {
        goodsIds: that.formData.goodsId,
        filmCode: that.formData.selectedFilm,
        lensQuantity: that.formData.lensQuantity,
      }
      if (uni.getStorageSync('shopId')) {
        params.shopId = uni.getStorageSync('shopId')
      }
      this.$http.POST('/app/order/order/createOrderBuyOrUpGoods', params, (res) => {
        if (res.code === 1000) {
          that.$tools.routerTo('/pages/index/orderDetail?orderId=' + res.data.orderId, 'navigateTo', 'none')
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }, (err) => {
        console.error('请求接口失败', err);
        uni.showToast({
          title: err.message,
          icon: 'none'
        });
      });
    },
    // 原始创建订单方法
    createOrder() {
      const that = this
      let params = {
        goodsIds: this.goodsIds.split(','),
      }
      if (uni.getStorageSync('shopId')) {
        params.shopId = uni.getStorageSync('shopId')
      }
      this.$http.POST('/app/order/order/createOrderByGoodsIds', params, (res) => {
        if (res.code === 1000) {
          that.$tools.routerTo('/pages/index/orderDetail?orderId=' + res.data.orderId, 'navigateTo', 'none')
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }, (err) => {
        console.error('请求接口失败', err);
        uni.showToast({
          title: err.message,
          icon: 'none'
        });
      });
    }
  }
}
</script>

<style>
.container {
  padding-bottom: 80rpx;
  background-color: #ffffff;
}

.section {
    background-color: #ffffff;
    margin-bottom: 20rpx;
    padding: 30rpx;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  }

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 30rpx;
  color: #333333;
}

/* 左右眼选择样式 */
.eye-select-container {
  display: flex;
  justify-content: space-between;
}

.eye-select-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1vw 0;
  margin: 0 1vw;
  transition: all 0.3s;
}

.eye-select-btn.active {
  border-color: #00BCD4;
  background-color: #e0f7fa;
}

.eye-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.eye-text {
  font-size: 28rpx;
  color: #333333;
}

.eye-select-btn.active .eye-text {
  color: #00BCD4;
}

.eye-image {
  width: 100%;
  max-width: 100%;
  height: auto;
}

/* 镜片选择样式 */
.lens-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.lens-item {
  height: 100%;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 20rpx;
  transition: all 0.3s;
}

.lens-item.active {
  border-color: #00BCD4;
  background-color: #e0f7fa;
}

.lens-image {
  width: 100%;
  height: 100%;
  /* margin-bottom: 20rpx; */
  border-radius: 8rpx;
  overflow: hidden;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}

.lens-name {
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 10rpx;
  color: #333333;
}

.lens-desc {
  font-size: 24rpx;
  color: #666666;
  line-height: 36rpx;
}

/* 价格信息样式 */
  .price-info-container {
    /* padding: 20rpx; */
    padding-left: 4vw;
  }

  .price-item {
    padding: 15rpx 0;
  }

  .price-value {
    font-size: 28rpx;
    color: #333333;
  }

  .price-value-icon {
    font-size: 5vw;
    color: #ff8c00;
    font-weight: bold;
    margin-right: 1vw;
  }

  .price-item.total-price .price-value.total {
    font-size: 12vw;
    color: #FCB735; /* 橙色 */
    font-weight: bold;
  }

/* 底部购买按钮样式 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.buy-button {
  width: 100%;
  height: 18vw;
  line-height: 18vw;
  background-color: #0fa79a;
  color: #ffffff;
  font-size: 5vw;
  border-radius: 5vw;
  border: none;
  text-align: center;
}

.buy-button::after {
  border: none;
}
</style>